﻿using Dapper;
using System;
using BCEntity.TMS.TransportOrder;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.TMS.TransportOrder
{
    /// <summary>
    /// 运输订单
    /// </summary>
    public class TransportOrderData : ITransportOrderData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM transportorder";
        private const string QUERY = @"SELECT TransportOrderId,OrderCount,CompleteCount,IgnoreCount,TransportAmount,ProvinceCode,ProvinceName,CityCode,CityName,CountyCode,CountyName,
                                            TransportOrderNo,Longitude,Latitude,EndProvinceCode,EndProvinceName,EndCityCode,EndCityName,EndCountyCode,EndCountyName,EndLongitude,
                                            EndLatitude,UserId,CreateTime,IsBook,BookTime,AssignTime,DriverOrderPromisingTime,CompleteTime,IsSplitOrder 
                                        FROM transportorder";
        public TransportOrderData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查运输订单是否存在
        public async Task<bool> Exists(long transportOrderId)
        {
            string sql = string.Format(@"{0} WHERE TransportOrderId=?TransportOrderId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TransportOrderId", transportOrderId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加运输订单
        public async Task<TransportOrderEntity> Add(TransportOrderEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("transportorder", new string[] { "OrderCount", "CompleteCount", "IgnoreCount", "TransportAmount", "ProvinceCode", 
                "ProvinceName", "CityCode", "CityName", "CountyCode", "CountyName", "TransportOrderNo", "Longitude", "Latitude", "EndProvinceCode", "EndProvinceName", 
                "EndCityCode", "EndCityName", "EndCountyCode", "EndCountyName", "EndLongitude", "EndLatitude", "UserId", "IsBook", "IsSplitOrder" });
            sql = string.Format("{0} {1} WHERE TransportOrderId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?OrderCount", entity.OrderCount, DbType.Int32, size: 11);
            parameters.Add("?CompleteCount", entity.CompleteCount, DbType.Int32, size: 11);
            parameters.Add("?IgnoreCount", entity.IgnoreCount, DbType.Int32, size: 11);
            parameters.Add("?TransportAmount", entity.TransportAmount, DbType.Decimal, size: 10);
            parameters.Add("?ProvinceCode", entity.ProvinceCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?ProvinceName", entity.ProvinceName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CityCode", entity.CityCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CityName", entity.CityName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CountyCode", entity.CountyCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CountyName", entity.CountyName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?TransportOrderNo", entity.TransportOrderNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?Longitude", entity.Longitude, DbType.Double);
            parameters.Add("?Latitude", entity.Latitude, DbType.Double);
            parameters.Add("?EndProvinceCode", entity.EndProvinceCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndProvinceName", entity.EndProvinceName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndCityCode", entity.EndCityCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndCityName", entity.EndCityName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndCountyCode", entity.EndCountyCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndCountyName", entity.EndCountyName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndLongitude", entity.EndLongitude, DbType.Double);
            parameters.Add("?EndLatitude", entity.EndLatitude, DbType.Double);
            parameters.Add("?UserId", entity.UserId, DbType.Int64, size: 20);
            parameters.Add("?IsBook", entity.IsBook, DbType.Boolean);
            parameters.Add("?IsSplitOrder", entity.IsSplitOrder, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<TransportOrderEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改运输订单
        public async Task<TransportOrderEntity> Update(TransportOrderEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("transportorder", new string[] { "OrderCount", "CompleteCount", "IgnoreCount", "TransportAmount", "ProvinceCode", "ProvinceName",
                "CityCode", "CityName", "CountyCode", "CountyName", "TransportOrderNo", "Longitude", "Latitude", "EndProvinceCode", "EndProvinceName", "EndCityCode", "EndCityName", 
                "EndCountyCode", "EndCountyName", "EndLongitude", "EndLatitude", "UserId", "IsBook", "BookTime", "AssignTime", "DriverOrderPromisingTime", "CompleteTime", 
                "IsSplitOrder" }, new string[] { "TransportOrderId" });
            sql = string.Format("{0} {1} WHERE TransportOrderId=?TransportOrderId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TransportOrderId", entity.TransportOrderId, DbType.Int64, size: 20);
            parameters.Add("?OrderCount", entity.OrderCount, DbType.Int32, size: 11);
            parameters.Add("?CompleteCount", entity.CompleteCount, DbType.Int32, size: 11);
            parameters.Add("?IgnoreCount", entity.IgnoreCount, DbType.Int32, size: 11);
            parameters.Add("?TransportAmount", entity.TransportAmount, DbType.Decimal, size: 10);
            parameters.Add("?ProvinceCode", entity.ProvinceCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?ProvinceName", entity.ProvinceName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CityCode", entity.CityCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CityName", entity.CityName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CountyCode", entity.CountyCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CountyName", entity.CountyName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?TransportOrderNo", entity.TransportOrderNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?Longitude", entity.Longitude, DbType.Double);
            parameters.Add("?Latitude", entity.Latitude, DbType.Double);
            parameters.Add("?EndProvinceCode", entity.EndProvinceCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndProvinceName", entity.EndProvinceName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndCityCode", entity.EndCityCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndCityName", entity.EndCityName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndCountyCode", entity.EndCountyCode?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndCountyName", entity.EndCountyName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EndLongitude", entity.EndLongitude, DbType.Double);
            parameters.Add("?EndLatitude", entity.EndLatitude, DbType.Double);
            parameters.Add("?UserId", entity.UserId, DbType.Int64, size: 20);
            parameters.Add("?IsBook", entity.IsBook, DbType.Boolean);
            parameters.Add("?BookTime", entity.BookTime, DbType.DateTime);
            parameters.Add("?AssignTime", entity.AssignTime, DbType.DateTime);
            parameters.Add("?DriverOrderPromisingTime", entity.DriverOrderPromisingTime, DbType.DateTime);
            parameters.Add("?CompleteTime", entity.CompleteTime, DbType.DateTime);
            parameters.Add("?IsSplitOrder", entity.IsSplitOrder, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<TransportOrderEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除运输订单
        public async Task<bool> Delete(long transportOrderId)
        {
            string sql = @"DELETE FROM transportorder WHERE TransportOrderId=?TransportOrderId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TransportOrderId", transportOrderId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取运输订单
        public async Task<TransportOrderEntity> GetEntity(long transportOrderId)
        {
            string sql = string.Format(@"{0} WHERE TransportOrderId=?TransportOrderId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TransportOrderId", transportOrderId, DbType.Int64);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<TransportOrderEntity>(sql, parameters);
        }
        #endregion

        #region 获取运输订单列表
        public async Task<IEnumerable<TransportOrderEntity>> GetList()
        {
            return await this.databaseContext.Master.QueryAsync<TransportOrderEntity>(QUERY);
        }
        #endregion

        #region 获取运输订单分页
        public async Task<(IEnumerable<TransportOrderEntity>, int)> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM transportorder {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.QueryMultipleAsync<TransportOrderEntity, int>(sql, parameters);
        }
        #endregion
    }
}



